package com.rao.gmall.item.config;

import com.rao.gmall.common.cache.GmallCacheAspect;
import com.rao.gmall.common.config.ItemRedissonConfig;
import com.rao.gmall.common.handler.GlobalExceptionHandler;
import feign.Logger;
import lombok.Data;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.*;

/**
 * @author nzmxfan
 * @create 2021-08-10-18:27
 */

/**
 * 工具类提取的所有自动配置类我们使用 @Import 即可
 * 导入自己的 GmallCacheAspect.class 分布式缓存切面
 */
@Import({ItemRedissonConfig.class, GmallCacheAspect.class, GlobalExceptionHandler.class})
@Configuration
//让 Spring Boot自己的RedisAutoConfiguration 配置完以后再启动我们的
@AutoConfigureAfter(RedisAutoConfiguration.class)
@EnableAspectJAutoProxy // 开启切面功能
public class ItemConfig {

    @Bean
    Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
    // 将自定义类作为参数传入自定义的业务线程池，且将线程池命名为 corePool
    @Bean("corePool")
    public ThreadPoolExecutor executor(ThreadConfigProperties properties) {
        return new ThreadPoolExecutor(properties.core,
                properties.max,
                properties.keepalive,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(properties.queueLength),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }

    // 读取配置文件的属性并创建 set、get 方法
    @Data
    @Component
    @ConfigurationProperties(prefix = "item-service.thread")
    class ThreadConfigProperties {
        private Integer core;
        private Integer max;
        private Long keepalive;
        private Integer queueLength;
    }

//    // 自定义线程池的名字
//    class MyItemServiceThreadFactory implements ThreadFactory {
//
//        @Override
//        public Thread newThread(Runnable r) {
//            Thread thread = new Thread();
//            thread.setName("item-service:" + UUID.randomUUID().toString().substring(0, 5));
//            return thread;
//        }
//    }
}
